import React, { PureComponent } from 'react';
import { Input, Icon } from 'antd';
import styles from './index.less';

export default class EditableItem extends PureComponent {
  state = {
    copyValue: '',
    editable: false,
  };

  handleChange = (e) => {
    const { value } = e.target;
    if (this.props.onChange) {
      this.setState({ copyValue: value });
    }
  }
  check = () => {
    this.setState({ editable: false });
    if (this.props.onChange) {
      this.props.onChange(this.state.copyValue);
    }
  }
  edit = () => {
    this.setState({ editable: true, copyValue: this.props.value });
  }
  render() {
    const { value } = this.props;
    const { copyValue, editable } = this.state;
    return (
      <div className={styles.editableItem}>
        {
          editable ?
            (
              <div className={styles.wrapper}>
                <Input
                  value={copyValue}
                  onChange={this.handleChange}
                  onBlur={this.check}
                  onPressEnter={this.check}
                />
                <Icon
                  type="check"
                  className={styles.icon}
                  onClick={this.check}
                />
              </div>
            ) :
            (
              <div className={styles.wrapper}>
                <span>{value}</span>
                <Icon
                  type="edit"
                  className={styles.icon}
                  onClick={this.edit}
                />
              </div>
            )
        }
      </div>
    );
  }
}
